<?php

namespace app\api\admin\v1\library;

use Swoole\Coroutine;
use zhanshop\App;
use zhanshop\ShellCommand;

class GitCommand
{
    public function execute($cmd, $callback)
    {
        $error = App::runtimePath().'/process/'.md5($cmd).'.log';
        $descriptorspec = array(
            0 => array("pipe", "r"),
            1 => array("pipe", "w"),
            2 => array("file", $error, "a")
        );

        $process = proc_open($cmd, $descriptorspec, $pipes);
        if($process == false) App::error()->setError($cmd.'启动失败');
        $isRun = true;
        Coroutine::create(function () use (&$pipes, &$isRun){
            while (true) {
                $msg = fread($pipes[1], 64);
                if($msg === ""){
                    $isRun = false;
                    break;
                }
            }
        });

        ShellCommand::exec("tail -f ".$error, function ($msg){
            var_dump($msg);
        });
        // 使用这两个命令结合实现
        @unlink($error);
        fclose($pipes[0]);
        proc_close($process);
    }
}